package com.qf.fmall2203.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2203.user.entity.Users;
import com.qf.fmall2203.user.mapper.UsersMapper;
import com.qf.fmall2203.user.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2203.user.vo.UserRegistVo;
import com.qf.fmall2203.utils.Constants;
import com.qf.fmall2203.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2023-02-13
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void regist(UserRegistVo userRegistVo) throws Exception {

        // 校验两次密码是否一致
        final String password = userRegistVo.getPassword();
        final String repassword = userRegistVo.getRepassword();

        final String username = userRegistVo.getUsername();

        if (!password.equals(repassword)){
            throw new Exception("密码不一致");
        }

        // 检查数据库中是否存在同名用户
        final Users dbuser = getOne(new QueryWrapper<Users>().eq("username", username));
        if (dbuser!=null){
            // 用户名已存在
            throw new Exception("用户名已经存在拉");
        }

        // 产生一个 随机 盐
        final String salt = SaltUtils.getSalt(Constants.SALT_LENTH);

        final Md5Hash md5Hash = new Md5Hash(password, salt, Constants.HASH_TIMES);

        // 产生密码
        final String md5Password = md5Hash.toHex();

        // 创建一个 user对象，赋值，并写入数据库
        final Users users = new Users();
        users.setUsername(username);
        users.setPassword(md5Password);
        users.setSalt(salt);

        users.setUserRegtime(new Date());
        users.setUserModtime(new Date());

        save(users);

    }
}
